package com.atguigu.gulimall.auth.controller;

import com.atguigu.common.constant.AuthConstant;
import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberEntityVo;
import com.atguigu.gulimall.auth.feign.MemberFeifnService;
import com.atguigu.gulimall.auth.feign.ThirdPartyService;
import com.atguigu.gulimall.auth.vo.MemberLoginVo;
import com.atguigu.gulimall.auth.vo.MemberRegistVo;
import com.atguigu.gulimall.auth.vo.UserLoginVo;
import com.atguigu.gulimall.auth.vo.UserResgistVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @program: gulimall
 * @description: 登录
 * @author: liuxvru
 * @create: 2024-08-26 02:03
 **/
@Slf4j
@Controller
public class LoginController {
    @Autowired
    private ThirdPartyService thirdPartyService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private MemberFeifnService memberFeifnService;

    @GetMapping("/sms/sendCode")
    @ResponseBody
    protected R sendCode(@RequestParam("phone") String phone) {
        log.debug("手机号：{}", phone);
        String s = redisTemplate.opsForValue().get(AuthConstant.SMS_CODE_CATCH_PREFIX + phone);
        if (s != null) {
            long createTime = Long.parseLong(s.split("_")[1]);
            if (System.currentTimeMillis() - createTime < 60000) {
                return R.error(BizCodeEnume.SMS_CODE_EXCEPTION.getCode(), BizCodeEnume.SMS_CODE_EXCEPTION.getMsg());
            }
        }
        Random random = new Random();
        String replace = ((Integer) (100000 + random.nextInt(900000))).toString();

        redisTemplate.opsForValue().set(AuthConstant.SMS_CODE_CATCH_PREFIX + phone, replace + "_" + System.currentTimeMillis(), 10, TimeUnit.MINUTES);

        thirdPartyService.send(phone, replace);
        return R.ok();
    }

    @PostMapping("/regist")
    protected String regist(@Valid UserResgistVo vo, BindingResult result, RedirectAttributes model) {
        if (result.hasErrors()) {
            Map<String, String> errors = new HashMap<>();
            result.getFieldErrors().forEach((item) -> {
                errors.put(item.getField(), item.getDefaultMessage());
            });
            model.addFlashAttribute("errors", errors);
            log.debug("注册信息有误：{}", errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }
        String s = redisTemplate.opsForValue().get(AuthConstant.SMS_CODE_CATCH_PREFIX + vo.getPhone());
        if (s != null&& s.split("_")[0].equals(vo.getCode())) {
            //注册
            MemberRegistVo memberRegistVo = new MemberRegistVo();
            BeanUtils.copyProperties(vo, memberRegistVo);
            R regist = memberFeifnService.regist(memberRegistVo);
            if(regist.getCode()!=0){
                Map<String, String> errors = new HashMap<>();
                errors.put("msg", regist.getData().toString());
                model.addFlashAttribute("errors", errors);
                return "redirect:http://auth.gulimall.com/reg.html";
            }
            //验证码通过 删除
            redisTemplate.delete(AuthConstant.SMS_CODE_CATCH_PREFIX + vo.getPhone());

        }else{
            Map<String, String> errors = new HashMap<>();
            errors.put("code", "验证码错误");
            model.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }
        return "redirect:http://auth.gulimall.com/login.html";
    }

    @PostMapping("/login")
    protected String login(@Valid UserLoginVo vo, HttpSession session, RedirectAttributes model) {
        MemberLoginVo memberLoginVo = new MemberLoginVo();
        BeanUtils.copyProperties(vo, memberLoginVo);
        R login = memberFeifnService.login(memberLoginVo);
        if(login.getCode()==0){
            MemberEntityVo poJo = R.toPoJo(login.get("data"), MemberEntityVo.class);
            session.setAttribute(AuthConstant.LOGIN_USER, poJo);
            return "redirect:http://gulimall.com/";
        }else{
            Map<String, String> errors = new HashMap<>();
            errors.put("msg", login.get("msg").toString());
            model.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }


    @GetMapping("/login.html")
    protected String loginPage(HttpSession session) {
        Object attribute = session.getAttribute(AuthConstant.LOGIN_USER);
        if(attribute!=null){
            return "redirect:http://gulimall.com/";
        }else {
            return "login";
        }
    }
}
